package com.example.personal.aiagent.user.login;

import com.example.personal.aiagent.user.mapper.UserMapper;
import com.example.personal.aiagent.user.model.dto.UserDTO;
import com.example.personal.aiagent.user.model.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 登录服务类
 */
@Service
@Slf4j
public class LoginServiceAbility implements UserDetailsService, UserDetailsPasswordService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity entity = userMapper.selectByUsername(username);
        if (entity == null) {
            throw new UsernameNotFoundException("user not found");
        }
        return UserDTO.entityToDTO(entity);
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        log.info("will update user:{} password", user.getUsername());
        UserEntity entity = userMapper.selectByUsername(user.getUsername());
        userMapper.updateUser(entity.getId(), entity.getUsername(), newPassword);
        newPassword = null;
        entity.setPassword(null);
        log.info("update user:{} password finish", user.getUsername());
        return user;
    }
}
